package cn.dakaqi.services.impl;

import cn.dakaqi.dao.CustomerDao;
import cn.dakaqi.entities.Customer;
import cn.dakaqi.services.CustomerService;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

import java.util.List;
import java.util.Map;

/**
 * Created by yangx
 * Date: 2016/7/19 0019
 * Time: 16:48
 */

@Component(value = "customerService")
@Transactional
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    CustomerDao customerDao;

    @Override
    public void saveCustomer(Customer customer) throws ServiceRuntimeException
    {
        if (null == customer)
            throw new ServiceRuntimeException("数据无效");
        customerDao.save(customer);
    }

    @Override
    public void updateCustomer(Customer customer) throws ServiceRuntimeException
    {
        if (null == customer)
            throw new ServiceRuntimeException("数据无效");
        customerDao.save(customer);
    }

    @Override
    public Customer findByCode(String code) throws ServiceRuntimeException
    {
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("customerCode", new SearchFilter("customerCode", SearchFilter.Operator.LIKE, code));
        Specification<Customer> spec = DynamicSpecifications.bySearchFilter(filters.values(), Customer.class);
        List<Customer> list = customerDao.findAll(spec);
        if(null == list || list.size() ==0)
            return null;
        else
            return list.get(0);
    }



}








